package com.example.lib.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.RelativeLayout
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.example.lib.databinding.AppTitleBarBinding
import com.example.lib.extend.dip2px
import com.example.lib.extend.gone
import com.example.lib.extend.setOnDoubleClickListener
import com.example.lib.extend.setWidthOrHeightNot2Px
import com.example.lib.extend.visi

class AppBar(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    RelativeLayout(context, attrs, defStyleAttr) {

    private val binding: AppTitleBarBinding = AppTitleBarBinding.inflate(LayoutInflater.from(context), this, true)

    /**
     * 设置title
     */
    fun setTitle(title: CharSequence?) {
        binding.AppbarTitle.text = title
    }

    /**
     * 设置title
     */
    fun setTitleImage(@DrawableRes resId: Int) {
        binding.root.setWidthOrHeightNot2Px(height = context.dip2px(100f))
        binding.AppbarTitle.gone()
        binding.AppbarImage.visi()
        binding.AppbarImage.setImageResource(resId)
    }

    /**
     * 设置title
     */
    fun setTitle(@StringRes resId: Int) {
        binding.AppbarTitle.text = resources.getString(resId)
    }

    /**
     * 设置title颜色
     */
    fun setTitleColor(@ColorInt color: Int) {
        binding.AppbarTitle.setTextColor(color)
    }

    /**
     * 设置title颜色
     */
    fun setAppBarColor(@ColorInt color: Int) {
        binding.AppbarHeader.setBackgroundColor(color)
    }

    /**
     * 设置右边文字和样式
     */
    fun setRightTextAndStyle(text: String, color: Int, click: () -> Unit = {}) {
        binding.AppbarRightText.visi()
        binding.AppbarRightText.text = text
        binding.AppbarRightText.setTextColor(context.getColor(color))
        binding.AppbarRightText.setOnDoubleClickListener { click.invoke() }
    }

    /**
     *  设置右边图片
     */
    fun setRightImageAndClick(image: Int, click: () -> Unit = {}) {
        binding.AppbarRight.visi()
        binding.AppbarRight.setImageResource(image)
        binding.AppbarRight.setOnDoubleClickListener { click.invoke() }
    }

    /**
     * 设置右边文字
     */
    fun setRightText(text: String) {
        binding.AppbarRightText.text = text
    }

    fun hideRight() {
        binding.AppbarRight.gone()
        binding.AppbarRightText.gone()
    }

    fun setOnCloseClick(image: Int = 0, click: () -> Unit = {}) {
        if (image != 0) binding.AppbarLeft.setImageResource(image)
        binding.leftParent.setOnDoubleClickListener {
            click.invoke()
        }
    }

    fun hideBottomLineView() {
        binding.AppbarBottomLineView.gone()
    }
}